package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.feign.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.TaskDto;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author 陈辉
 * @data 2023 11:29
 */
@Service
@Slf4j
@Transactional
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private IScheduleClient scheduleClient;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 添加任务到延迟队列中
     *
     * @param id          文章的id
     * @param publishTime 发布的时间  可以做为任务的执行时间
     */
    @Override
    @Async
    public void addNewsToTask(Integer id, Date publishTime) {
        TaskDto dto = new TaskDto();

        //设置任务类型
        dto.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        //设置任务优先级
        dto.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        //设置任务执行时间
        dto.setExecuteTime(publishTime.getTime());
        //设置任务执行参数
        dto.setParameters(id.toString().getBytes());


        scheduleClient.addTask(dto);
    }

    /**
     * 定时拉取任务，进行文章审核
     */
    @Override
    @Scheduled(cron = "0 0/1 * * * ?")
    public void scanNewsByTask() {
        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(),
                TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        if (responseResult.getCode().equals(200) && responseResult.getData() != null){
            log.info("文章审核---消费任务执行---begin---");
            //拉到任务，就消费：使用WmNewsAutoScanService进行文章审核
            TaskDto dto = JSON.parseObject(JSON.toJSONString(responseResult.getData()), TaskDto.class);
            byte[] parameters = dto.getParameters();
            String newsId = new String(parameters);
            wmNewsAutoScanService.autoScanWmNews(Integer.valueOf(newsId));
            log.info("文章审核---消费任务执行---end---");
        }
    }
}
